package com.xnyzc.lhy.didi.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.net.URL;

/**
 * 高德地图  根据地名获取经纬度，
 *          根据经纬度获取地址
 */
public class GaoDeMapUtil {

    /**
     * 根据经纬度获取地址
     * @param location 坐标字符串-->经度 , 纬度
     * @return
     */
    public static StringBuffer getAddress(String location){
        String urlString = "http://restapi.amap.com/v3/geocode/regeo?key=8325164e247e15eea68b59e89200988b&s=rsv3&location="+location+
                "&radius=2800&callback=jsonp_452865_&platform=JS&logversion=2.0&sdkversion=1.3" +
                "&appname=http%3A%2F%2Flbs.amap.com%2Fconsole%2Fshow%2Fpicker&csid=49851531-2AE3-4A3B-A8C8-675A69BCA316";
        String res = "";
        StringBuffer detailedAddress  = new StringBuffer();
        try {
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line+"\n";
            }
            in.close();
        } catch (Exception e) {
            System.out.println("根据坐标获取地址resError--->" + e.getMessage());
            return null;
        }
        System.out.println("res-->" + res);
        if(res == null || res == ""){//确保res有信息
            return null;
        }
        try{
            //去除（），转换为json格式
            String json = res.substring(res.indexOf("(")+1,res.lastIndexOf(")"));
            JSONObject jsonObject = JSONObject.parseObject(json);
            System.out.println("jsonObject--->" + jsonObject);
            //
            JSONObject jsonObject2 = JSONObject.parseObject(jsonObject.get("regeocode").toString());
            System.out.println("jsonObject2--->" + jsonObject2);
            //
            JSONObject jsonObject3 = JSON.parseObject(jsonObject2.get("addressComponent").toString());
            System.out.println("jsonObject3--->" + jsonObject3);
            //国家
            String country = jsonObject3.get("country").toString();
            //省份
            String province = jsonObject3.get("province").toString();
            //城市
            String city = jsonObject3.get("city").toString();
            //城区
            String district = jsonObject3.get("district").toString();
            //用StringBuffer拼接（安全考虑）
            detailedAddress.append(country);
            detailedAddress.append(",");
            detailedAddress.append(province);
            detailedAddress.append(",");
            detailedAddress.append(city);
            detailedAddress.append(",");
            detailedAddress.append(district);
        }catch (Exception e){
            System.out.println("根据坐标获取地址jsonError--->" + e.getMessage());
            return null;
        }
        return detailedAddress;
    }

    /**
     * 根据地名获取经纬度
     * @param address 详细地址
     * @param name  详细公司名或者详细地方名字
     * @return
     */
    public static String getLocation(String address,String name){
        String urlString = "http://restapi.amap.com/v3/place/text?" +
                "s=rsv3&children=&key=8325164e247e15eea68b59e89200988b&page=1&" +
                "offset=10&city=610100&language=zh_cn&callback=jsonp_25126_&" +
                "platform=JS&logversion=2.0&sdkversion=1.3&appname=http%3A%2F%2Flbs.amap.com%2Fconsole%2Fshow%2Fpicker" +
                "&csid=19FA0D45-180F-4D45-BCB4-C6C265F55FF6&keywords="+address+name;
        String res = "";
        //坐标
        String location = null;
        try {
            //http://restapi.amap.com/v3/geocode/regeo?key=8325164e247e15eea68b59e89200988b&s=rsv3&location=101.539737903028,36.79828256329313&radius=2800&callback=jsonp_452865_&platform=JS&logversion=2.0&sdkversion=1.3&appname=http%3A%2F%2Flbs.amap.com%2Fconsole%2Fshow%2Fpicker&csid=49851531-2AE3-4A3B-A8C8-675A69BCA316
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line+"\n";
            }
            in.close();
        } catch (Exception e) {
            System.out.println("根据地名获取坐标resError---> " + e.getMessage());
            return null;
        }
        System.out.println("res-->" + res);
        if(res == null || res == ""){//确保res有信息
            return null;
        }
        try{
            //去除（），转换为json格式
            String json = res.substring(res.indexOf("(")+1,res.lastIndexOf(")"));
            JSONObject jsonObject = JSONObject.parseObject(json);
            System.out.println("jsonObject--->" + jsonObject);
            //得到周围所有信息集合
            JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("pois").toString());
            System.out.println("jsonArray--->" + jsonArray);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                String resultName = jsonObject2.get("name").toString();
                if(name.equals(resultName)){//确保正确位置
                    location = jsonObject2.get("location").toString();
                }
            }
        }catch (Exception e){
            System.out.println("根据地名获取坐标jsonError--->" + e.getMessage());
            return null;
        }

        return location;
    }

    /**
     * 开发者测试使用
     * @param agrs
     */
    public static void main(String[] agrs) {
        //根据坐标获取地址
        StringBuffer detailedAddress = getAddress("103.95585,30.569907");//经度 , 纬度
        System.out.println("detailedAddress-->" + detailedAddress);

        //根据地名获取坐标
        String location = getLocation("四川省成都市武侯区九兴大道10", "泰山科技大厦");
        System.out.println("location--->" + location);
    }
}
